package com.xinzhitong.www.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xinzhitong.www.exception.*;
import com.xinzhitong.www.exception.apply.ApplyRepetitionException;
import com.xinzhitong.www.exception.train.*;
import com.xinzhitong.www.exception.trainclassgeneral.NoTrainClassGeneralException;
import com.xinzhitong.www.exception.trainclassnameandno.NoTrainClassNameAndNoException;
import com.xinzhitong.www.exception.traincontact.NoTrainContactException;
import com.xinzhitong.www.exception.traingeneral.NoTrainGeneralException;
import com.xinzhitong.www.exception.trainmanager.InCorrectStateException;
import com.xinzhitong.www.exception.trainnameandidbyprofessionid.NoTrainNameAndIdByProfessionIdException;
import com.xinzhitong.www.exception.traintable.NoTrainTimeException;
import com.xinzhitong.www.exception.userenrolltrainclasscondition.NoUserEnrollTrainClassConditionException;
import com.xinzhitong.www.mapper.ClickMapper;
import com.xinzhitong.www.mapper.SystemMessageMapper;
import com.xinzhitong.www.mapper.TrainMapper;
import com.xinzhitong.www.pojo.*;
import com.xinzhitong.www.service.TrainService;
import com.xinzhitong.www.utils.FileHelper;
import com.xinzhitong.www.utils.MyPageInfo;
import com.xinzhitong.www.utils.SearchKeyUtil;
import com.xinzhitong.www.utils.StuListExcel;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 培训服务实现
 *
 * @author 魏骆淳 钟伟良
 */
@Service
@Transactional
public class TrainServiceImpl implements TrainService {

    /**
     * 默认文本
     */
    public static String defaultText = "default";

    @Resource
    private TrainMapper trainMapper;

    @Resource
    private ClickMapper clickMapper;

    @Resource
    private SystemMessageMapper systemMessageMapper;

    @Override
    public Map<String, Object> getTrainInformation(Integer trainId) throws NullTrainInformationException {
        Train trainInformation = trainMapper.selectTrainInformation(trainId);
        List<TrainClass> trainClassNoSum = trainMapper.selectTrainClassInformation(trainId);
        if (trainInformation == null || trainClassNoSum.size() == 0) {
            throw new NullTrainInformationException();
        } else {
            List<Long> trainClassNo = new ArrayList<>();
            for (TrainClass trainClass : trainClassNoSum) {
                trainClassNo.add(trainClass.getNo());
            }
            Map<String, Object> map = new HashMap<>();
            map.put("trainIntroduction", trainInformation.getIntroduction());
            map.put("trainClassNo", trainClassNo);
            return map;
        }
    }

   /* @Override
    public Map<String, Object> getTrainClassLocation(
            Integer trainId,
            Integer trainClassNo) throws NullTrainClassLocationException {
        List<TrainClassLocation> trainClassLocation = trainMapper.selectTrainClassLocation(trainId, trainClassNo);
        if (trainClassLocation.size() == 0) {
            throw new NullTrainClassLocationException();
        } else {
            List<String> trainClassLocationSum = new ArrayList<>();
            for (TrainClassLocation trainClassLocationOne : trainClassLocation) {
                trainClassLocationSum.add(
                        trainClassLocationOne.getProvince() +
                                trainClassLocationOne.getCity() +
                                trainClassLocationOne.getArea() +
                                trainClassLocationOne.getAddress()
                );
            }
            Map<String, Object> map = new HashMap<>();
            map.put("trainClassLocation", trainClassLocationSum);
            return map;
        }
    }

    @Override
    public Map<String, Object> getTrainClassTime(
            Integer trainId,
            Integer trainClassNo) throws NullTrainClassTimeException {
        List<Map<String, Object>> trainClassTime = trainMapper.selectTrainClassTime(trainId, trainClassNo);
        if (trainClassTime.size() == 0) {
            throw new NullTrainClassTimeException();
        } else {
            List<String> trainClassTimeSum = new ArrayList<>();
            for (Map<String, Object> stringObjectMap : trainClassTime) {
                trainClassTimeSum.add(
                        stringObjectMap.get("startTime").toString() + "--" +
                                stringObjectMap.get("endTime").toString()
                );
            }
            Map<String, Object> map = new HashMap<>();
            map.put("trainClassTime", trainClassTimeSum);
            return map;
        }
    }*/

    @Override
    public List<Map<String, Object>> getTrainClassLocation(
            Integer trainId,
            Integer trainClassNo) throws NullTrainClassLocationException {
        List<Map<String, Object>> trainClassLocation = trainMapper.selectTrainClassLocation(trainId, trainClassNo);
        if (trainClassLocation.size() == 0) {
            throw new NullTrainClassLocationException();
        } else {
            return trainClassLocation;
        }
    }

    @Override
    public List<Map<String, Object>> getTrainClassTime(
            Integer trainId,
            Integer trainClassNo) throws NullTrainClassTimeException {
        Timestamp d = new Timestamp(System.currentTimeMillis());
        String datetime = d.toString();
        List<Map<String, Object>> trainClassTime = trainMapper.selectTrainClassTime(trainId, trainClassNo, datetime);
        if (trainClassTime.size() == 0) {
            throw new NullTrainClassTimeException();
        } else {

            for(int i=0;i<trainClassTime.size();i++){
                String x = trainClassTime.get(i).get("start_time").toString();
                trainClassTime.get(i).put("Start_time_new",x);
                x = trainClassTime.get(i).get("end_time").toString();
                trainClassTime.get(i).put("End_time_new",x);
                trainClassTime.get(i).remove("start_time").toString();
                trainClassTime.get(i).remove("end_time").toString();
            }
            return trainClassTime;
        }
    }

    @Override
    public Map<String, Object> getTrainClassInformation(
            Integer trainId,
            Integer trainClassNo
    ) throws NullTrainClassInformationException {
        TrainClass trainClassText = trainMapper.selectTrainClassText(trainId, trainClassNo);
        List<TrainHasPicture> trainPicture = trainMapper.selectTrainPicture(trainId);
        List<TrainClassRequest> trainClassRequestSum = trainMapper.selectTrainClassRequest(trainId, trainClassNo);

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        String usn = user.getUsername();

        Timestamp d = new Timestamp(System.currentTimeMillis());
        clickMapper.insertUserClickTrainClassTime(usn,trainClassNo);
        if (trainClassText == null || trainPicture.size() == 0 || trainClassRequestSum.size() == 0) {
            throw new NullTrainClassInformationException();
        } else {
            List<String> trainClassRequest = new ArrayList<>();
            for (TrainClassRequest trainClassRequest1 : trainClassRequestSum) {
                trainClassRequest.add(trainClassRequest1.getText());
            }
            TrainHasPicture trainPictureFirst = trainPicture.get(0);
            Map<String, Object> map = new HashMap<>();
            map.put("trainClassRequest", trainClassRequest);
            map.put("trainPicture", FileHelper.fileURL + trainPictureFirst.getPicture());
            map.put("trainClassText", trainClassText.getText());
            return map;
        }
    }

    @Override
    public MyPageInfo getTrainOutline(
            Integer professionalId,
            Integer pageNo,
            Integer pageSize
    ) throws NullTrainOutlineException {
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String, Object>> trainOutline = trainMapper.selectTrainOutline(professionalId);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(trainOutline);
        if (trainOutline.size() == 0) {
            throw new NullTrainOutlineException();
        } else {
            for (Map<String, Object> train : pageInfo.getList()) {
                List<TrainHasPicture> trainPicture = trainMapper.selectTrainPicture((Integer) train.get("id"));
                if (trainPicture.size() == 0) {
                    throw new NullTrainOutlineException();
                } else {
                    TrainHasPicture trainPictureFirst = trainPicture.get(0);
                    train.put("trainPicture", FileHelper.fileURL + trainPictureFirst.getPicture());
                }
            }
            return new MyPageInfo(pageInfo);
        }
    }

    @Override
    public void getTrainClassApply(Integer trainClassTimeId) throws ApplyRepetitionException {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        List<UserHasTrainClassTime> trainClassTime =
                trainMapper.selectTrainClassTimeId(trainClassTimeId);
        if ((trainClassTime.size() == 0)) {
            throw new NullTrainClassTimeException();
        } else {
            UserHasTrainClassTime userHasTrainClassTime =
                    trainMapper.selectTrainApplyInformation(user.getUsername(), trainClassTimeId);
            if (userHasTrainClassTime == null) {
                trainMapper.insertTrainApplyInformation(user.getUsername(), trainClassTimeId);
            } else {
                throw new ApplyRepetitionException();
            }
        }
    }

    @Override
    public Map<String, Object> getTrainClass(Integer trainId) throws NullTrainClassException {
        List<TrainClass> trainClassInformation = trainMapper.selectTrainClassInformation(trainId);
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        List<Map<String, Object>> trainClassStudy = trainMapper.selectTrainClassStudy(trainId, user.getUsername());
        if (trainClassInformation.size() == 0 || trainClassStudy.size() == 0) {
            throw new NullTrainClassException();
        } else {
            List<Object> trainClassNoAndName = new ArrayList<>();
            List<String> trainClassStudySum = new ArrayList<>();
            for (TrainClass trainClass : trainClassInformation) {
                Map<String, Object> trainClassNoAndName1 = new HashMap<>();
                trainClassNoAndName1.put("trainClassNo", trainClass.getNo());
                trainClassNoAndName1.put("trainClassName", trainClass.getName());
                trainClassNoAndName.add(trainClassNoAndName1);
            }
            for (Map<String, Object> stringObjectMap : trainClassStudy) {
                trainClassStudySum.add(stringObjectMap.get("trainClassNo").toString());
            }
            Map<String, Object> map = new HashMap<>();
            map.put("trainClassNoAndName", trainClassNoAndName);
            map.put("trainClassStudy", trainClassStudySum);
            return map;
        }
    }

    @Override
    public Map<String, Object> getTrainClassApplyInformation(
            Integer trainClassTimeId
    ) throws TrainException {
        Map<String, Object> trainClassApplyInformation = trainMapper.selectTrainClassApplyInformation(trainClassTimeId);
        if (trainClassApplyInformation == null) {
            throw new NullTrainClassApplyInformationException();
        } else {
            List<TrainClassRequest> trainClassRequestSum = trainMapper.selectTrainClassRequest(
                    (Integer) trainClassApplyInformation.get("trainId"),
                    (Integer) trainClassApplyInformation.get("trainClassNo")
            );
            if (trainClassRequestSum.size() == 0) {
                throw new NullTrainClassApplyInformationException();
            } else {
                String trainClassTime =
                        trainClassApplyInformation.get("startTime") + "--" + trainClassApplyInformation.get("endTime");
                List<String> trainClassRequest = new ArrayList<>();
                for (TrainClassRequest trainClassRequest1 : trainClassRequestSum) {
                    if (trainClassRequest1.getBeChecked()) {
                        trainClassRequest.add(trainClassRequest1.getText());
                    }
                }
                trainClassApplyInformation.put("trainClassRequest", trainClassRequest);
                trainClassApplyInformation.put("trainClassTime", trainClassTime);
                trainClassApplyInformation.remove("trainClassTimeId");
                trainClassApplyInformation.remove("trainId");
                trainClassApplyInformation.remove("trainClassNo");
                trainClassApplyInformation.remove("startTime");
                trainClassApplyInformation.remove("endTime");
                return trainClassApplyInformation;
            }
        }
    }

    @Override
    public List<Map<String, Object>> getTrainGeneral(String time, String city, Integer trainId, Integer trainClassNo)
            throws TrainGeneralException {

        List<Map<String, Object>> x = trainMapper.selectTrainGeneral(time, city, trainId, trainClassNo);
        if (x.size() == 0)
            throw new NoTrainGeneralException();
        for (Map<String, Object> temp : x) {
            String a = (String) temp.get("start_time") + '-' + temp.get("end_time");
            temp.put("trainTime", a);
            temp.remove("start_time");
            temp.remove("end_time");
            if ((long) temp.get("enrollNumber") <= (long) temp.get("numberLimit")) {
                temp.put("enroll", true);
            } else {
                temp.put("enroll", false);
            }
            temp.put("contact", trainMapper.selectTrainGeneralContact((Integer) temp.get("id")));
            temp.put("trainOrganId", temp.get("train_organ_id"));
            temp.put("picture", FileHelper.fileURL + temp.get("picture"));
            temp.remove("train_organ_id");
        }

        return x;
    }

    @Override
    public List<TrainContact> getContact(Integer trainOrganId) throws TrainContactException {
        List<TrainContact> x = trainMapper.selectContact(trainOrganId);
        if (x.size() == 0)
            throw new NoTrainContactException();

        return x;
    }

    @Override
    public List<Map<String, Object>> getUserTrain(Integer year, Integer month) throws TrainTableException {
        Integer month1 = month + 1;
        String y = String.valueOf(year);
        String m = String.valueOf(month);
        String m1 = String.valueOf(month1);
        String time1 = y + '-' + m + '-' + "01 00:00:00";
        String time2 = y + '-' + m1 + '-' + "01 00:00:00";
        Date Time1;
        Date Time2;
        List<Map<String, Object>> b = new ArrayList<>();
        java.text.SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Time1 = formatter.parse(time1);
            Time2 = formatter.parse(time2);
            Subject subject = SecurityUtils.getSubject();
            User user = (User) subject.getPrincipal();
            List<String> z = trainMapper.selectTime(user.getUsername(), Time1, Time2);

            Integer a = trainMapper.selectDay(user.getUsername());
            if (a == null)
                throw new NoTrainTimeException();
            Map<String, Object> c = new HashMap<>();
            Map<String, Object> d = new HashMap<>();
            c.put("trainDay", z);
            d.put("dayDiff", a);
            b.add(c);
            b.add(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return b;
    }

    @Override
    public Map<String, Object> getTrainSystemMessage(Integer trainClassTimeId) throws TrainException {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Map<String, Object> trainSystemMessage =
                trainMapper.selectTrainSystemMessage(user.getUsername(), trainClassTimeId);
        if (trainSystemMessage == null) {
            throw new NullTrainSystemMessage();
        } else {
            trainSystemMessage.put("applyState", "报名成功");
            trainSystemMessage.put("announcements", "可在'我的课表'中查看培训时间");
            trainSystemMessage.put("question", "请拨打137-5085-0109");
            return trainSystemMessage;
        }
    }

    @Override
    public String underTrainClass(Integer id) {
        Integer x = trainMapper.updateTrainClass(id);
        String a;
        if (x == 1)
            a = "已下架此培训课次";
        else
            a = "请勿重复下架";
        return a;
    }

    @Override
    public String deleteTrainClass(List<Integer> idList) {
        String a;
        for (Integer id : idList) {
            trainMapper.deleteTrainClassTime(id);
        }
        a = "培训课次删除成功";
        return a;
    }

    @Override
    public List<Map<String, Object>> selectTrainClassNameAndNo(Integer trainId) throws TrainClassNameAndNoException {
        List<Map<String, Object>> x = trainMapper.selectTrainClassNoAndName(trainId);
        if (x.size() == 0)
            throw new NoTrainClassNameAndNoException();
        return x;
    }

    @Override
    public List<Map<String, Object>> selectTrainNameAndIdByProfessionId(Integer professionId)
            throws TrainNameAndIdByProfessionIdException {

        List<Map<String, Object>> x = trainMapper.selectTrainNameAndId(professionId);
        if (x.size() == 0)
            throw new NoTrainNameAndIdByProfessionIdException();
        return x;
    }

    @Override
    public MyPageInfo getTrainClassGeneral(String state, String name, Integer pageNo, Integer pageSize)
            throws TrainClassGeneralException {
        PageHelper.startPage(pageNo, pageSize);
        String name1 = SearchKeyUtil.makeKey(name);
        String state1 = SearchKeyUtil.makeKey(state);

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        List<Map<String, Object>> x = trainMapper.selectTrainClassGeneral(name1, state1, user.getUsername());
        if (x.size() == 0)
            throw new NoTrainClassGeneralException();

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(x);
        for (Map<String, Object> temp : pageInfo.getList()) {
            if (temp.get("publishTime") == null)
                temp.put("publishTime", null);
            else
                temp.replace("publishTime", temp.get("publishTime").toString());
        }
        return new MyPageInfo(pageInfo);
    }

    @Override
    public List<Map<String, Object>> getTrainClassEnrollCondition(Integer trainClassId) throws
            UserEnrollTrainClassConditionException {
        List<Map<String, Object>> x = trainMapper.SelectUserEnrollTrainClassCondition(trainClassId);
        if (x.size() == 0)
            throw new NoUserEnrollTrainClassConditionException();
        for (Map<String, Object> temp : x) {
            temp.putIfAbsent("contact", null);
            temp.putIfAbsent("userId", null);
            temp.putIfAbsent("realname", null);
            temp.replace("date", temp.get("date").toString());
        }
        return x;
    }

    @Override
    public String downloadTrainClassEnrollCondition(Integer trainClassId)
            throws UserEnrollTrainClassConditionException {
        List<Map<String, Object>> x = trainMapper.SelectUserEnrollTrainClassCondition(trainClassId);
        if (x.size() == 0)
            throw new NoUserEnrollTrainClassConditionException();

        String z = StuListExcel.stulist(x);
        return z;
    }

    public Map<String, Object> getTrainBasicInformation(Integer trainClassTimeId) throws TrainException {
        Map<String, Object> trainBasicInformation = trainMapper.selectTrainClassTimeBasicInformation(trainClassTimeId);
        if (trainBasicInformation == null) {
            throw new NullTrainClassTimeException();
        } else {
            String time = trainBasicInformation.get("startTime") + "--" + trainBasicInformation.get("endTime");
            trainBasicInformation.remove("startTime");
            trainBasicInformation.remove("endTime");
            trainBasicInformation.put("time", time);
            return trainBasicInformation;
        }
    }

    @Override
    public Map<String, Object> getTrainIndex(Integer trainClassTimeId) throws TrainException {
        Map<String, Object> trainClassTimeIndex = trainMapper.selectTrainClassTimeIndex(trainClassTimeId);
        if (trainClassTimeIndex == null) {
            throw new NullTrainClassTimeException();
        } else {
            return trainClassTimeIndex;
        }
    }

    @Override
    public void releaseTrain(
            Integer trainId,
            Integer trainClassNo,
            String startTime,
            String endTime,
            Integer requirePopulation,
            double fee,
            String contact,
            String startClock,
            String endClock
    ) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Integer trainOrganId = trainMapper.selectTrainOrganId(user.getUsername());
        String state = "待审核";
        trainMapper.insertGood();
        trainMapper.insertTrainClassTime(
                trainId,
                trainClassNo,
                startTime,
                endTime,
                requirePopulation,
                fee,
                contact,
                startClock,
                endClock,
                state,
                trainOrganId,
                trainMapper.selectLastInsertId()
        );
        trainCache.clear();
    }

    @Override
    public Map<String, Object> getTrainTotalInformation(Integer trainClassTimeId) throws TrainException {
        TrainClassTime trainClassTime = trainMapper.selectTrainClassTimeBYId(trainClassTimeId);
        if (trainClassTime == null) {
            throw new NullTrainClassTimeException();
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("startTime", trainClassTime.getStartTime());
            map.put("contact", trainClassTime.getContact());
            map.put("startClock", trainClassTime.getStartClock());
            map.put("endClock", trainClassTime.getEndClock());
            map.put("endTime", trainClassTime.getEndTime());
            map.put("requirePopulation", trainClassTime.getNumberLimit());
            map.put("fee", trainClassTime.getPrice());
            map.put("trainId", trainClassTime.getTrainId());
            map.put("trainClassNo", trainClassTime.getTrainClassNo());
            map.put("professionId", trainMapper.selectProfessionIdByTrainClassTimeId(trainClassTimeId));
            return map;
        }
    }

    @Override
    public void editTrain(
            Integer trainClassTimeId,
            Integer trainId,
            Integer trainClassNo,
            String startTime,
            String endTime,
            Integer requirePopulation,
            double fee,
            String contact,
            String startClock,
            String endClock
    ) {
        trainMapper.updateTrainClassTime(
                trainId,
                trainClassNo,
                startTime,
                endTime,
                requirePopulation,
                fee,
                contact,
                startClock,
                endClock,
                trainClassTimeId
        );
        trainCache.clear();
    }

    @Override
    public void saveTrain(Map<String, Object> map) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        trainCache.put(user.getUsername(), map);
    }

    @Override
    public Map<String, Object> getSavedTrain() throws TrainException {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Map<String, Object> map = trainCache.get(user.getUsername());
        if (map == null) {
            throw new NullTrainSavedException();
        } else {
            return map;
        }
    }

    /**
     * 培训缓存
     */
    private static Cache<String, Map<String, Object>> trainCache;

    static {
        //初始化缓存
        //缓存管理器
        EhCacheManager cacheManager = new EhCacheManager();
        cacheManager.setCacheManagerConfigFile("classpath:Train-ehcache-setting.xml");
        trainCache = cacheManager.getCache("trainCache");
    }

    @Override
    public Integer getTrainClassNewEnroll() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Map<String, Object> x = trainMapper.SelectLastTime(user.getUsername());
        Date date = new Date();

        Timestamp time = new Timestamp(date.getTime());
        Timestamp lastTime = time;
        if (x != null) {
            lastTime = (Timestamp) x.get("last_login_time");
        }
        if (trainMapper.SelectNewTrainClass(time, user.getUsername()) == null)
            return 0;
        return trainMapper.SelectNewTrainClass(time, user.getUsername()).size() -
                trainMapper.SelectNewTrainClass(lastTime, user.getUsername()).size();
    }

    @Override
    public Map<String, Object> getRecentEditorTrainClassTime() throws TrainException {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        List<Map<String, Object>> recentEditorTrainClassTime =
                trainMapper.selectRecentEditorTrainClassTime(user.getUsername());
        if (recentEditorTrainClassTime.size() == 0) {
            throw new NullRecentEditorTrainClassTime();
        } else {
            for (Map<String, Object> stringObjectMap : recentEditorTrainClassTime) {
                if (stringObjectMap.get("state").equals("已发布")) {
                    stringObjectMap.put("state", String.valueOf(stringObjectMap.get("publishTime")));
                }
                stringObjectMap.remove("publishTime");
            }
            return recentEditorTrainClassTime.get(0);
        }
    }

    @Override
    public Map<String, Object> getTrainBasicInformation2(Integer trainClassTimeId) throws TrainException {
        Map<String, Object> trainBasicInformation = trainMapper.selectTrainClassTimeBasicInformation(trainClassTimeId);
        String publicTime = trainMapper.selectPublicTimeByTrainClassTimeId(trainClassTimeId);
        if (trainBasicInformation == null) {
            throw new NullTrainClassTimeException();
        } else {
            if (publicTime == null) {
                publicTime = "未发布";
            }
            trainBasicInformation.remove("startTime");
            trainBasicInformation.remove("endTime");
            trainBasicInformation.put("publicTime", publicTime);
            return trainBasicInformation;
        }
    }

    @Override
    public MyPageInfo getTrainClassGeneral(
            String keyWord,
            Integer credentialId,
            String state,
            Integer pageNo,
            Integer pageSize
    ) throws NoTrainClassGeneralException {
        keyWord = SearchKeyUtil.makeKey(keyWord);
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String, Object>> trainClassGeneral =
                trainMapper.selectTrainClassGeneralByKeyWordAndCredential(keyWord, credentialId, state);
        if (trainClassGeneral.size() == 0)
            throw new NoTrainClassGeneralException();
        // 添加图片链接域名部分
        String key = "picture";
        for (Map<String, Object> tmp : trainClassGeneral)
            tmp.put(key, FileHelper.fileURL + tmp.get(key));

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(trainClassGeneral);
        return new MyPageInfo(pageInfo);
    }

    @Override
    public Map<String, Object> getTheTrainClassSummary(Integer trainClassTimeId) {
        Map<String, Object> summary = trainMapper.selectTrainClassTimeSummaryWithPicture(trainClassTimeId);
        if (summary == null)
            throw new NoTrainClassNameAndNoException();
        if (summary.get("picture") != null)
            summary.put("picture", FileHelper.fileURL + summary.get("picture"));
        return summary;
    }

    @Override
    public void publishTheTrainClassTime(Integer trainClassTimeId, String text) {
        TrainClass train = checkAndGetTrainClass(trainClassTimeId);
        if (trainMapper.updateStateOfTrainClassTime(trainClassTimeId, "已发布") == 0)
            throw new BusyException();
        Map<String, Object> map = trainMapper.selectTrainClassTimeById(trainClassTimeId);
        if (text.equals(defaultText))
            text = "您提交的\"" + train.getText() + "\"课次信息已通过审核，请通过查看培训了解更多详情";
        systemMessageMapper.insertSystemMessage((String) map.get("username"), "培训发布成功", text, "");
    }

    @Override
    public void rejectTheTrainClassTime(Integer trainClassTimeId, String text) {
        TrainClass train = checkAndGetTrainClass(trainClassTimeId);
        if (trainMapper.updateStateOfTrainClassTime(trainClassTimeId, "未通过") == 0)
            throw new BusyException();
        Map<String, Object> map = trainMapper.selectTrainClassTimeById(trainClassTimeId);
        if (text.equals(defaultText))
            text = "您提交的\"" + train.getText() + "\"课次信息未通过审核，请通过查看培训了解更多详情";
        systemMessageMapper.insertSystemMessage((String) map.get("username"), "培训发布成功", text, "");
    }

    /**
     * 检查培训课次id是否合法并返回对应的培训信息
     *
     * @param trainClassTimeId 培训课次id
     * @return 培训信息
     */
    TrainClass checkAndGetTrainClass(Integer trainClassTimeId) {
        TrainClassTime trainClassTime = trainMapper.selectTrainClassTimeBYId(trainClassTimeId);
        if (trainClassTime == null)
            throw new NoTrainClassNameAndNoException();
        if (!trainClassTime.getState().equals("待审核"))
            throw new InCorrectStateException();
        return trainMapper.selectTrainClassText(trainClassTime.getTrainId(), trainClassTime.getTrainClassNo());
    }

}
